#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <cstring>

using namespace std;

void handler(int sig)
{
    cout << "get a signal number: " << sig << endl;
    exit(0);
}

int main()
{
    signal(SIGSEGV, handler);
    int* p = nullptr;//野指针
    *p = 100;//访问野指针
    while(true) sleep(1);
    return 0;
}



/*
int main()
{
    signal(SIGFPE, handler);
    //除0错误
    int a = 10;
    a /= 0;
    while(true) sleep(1);
    return 0;
}
*/


/*
void handler(int sig)
{
    cout << "get a signal number: " << sig << endl;
    unsigned int n = alarm(5);
    cout << "还剩下" << n << "时间" << endl;
}
int main()
{
    // 发送SIGALRM信号 - Term 终止进程
    //signal(SIGALRM, handler);
    // 设定一个闹钟
    // 闹钟只会响一次

    alarm(10);//让闹钟提前响
    alarm(5);//让闹钟提前响
    int cnt = 0;
    while(true)
    {
        sleep(1);
        cout << "pid:" << getpid() << endl;
    }
    return 0;
}
*/

/*
void handler(int sig)
{
    cout << "get a signal number: " << sig << endl;
    cout << "g_val " << g_val << endl;
    exit(0);
}
int main()
{
    // 发送SIGALRM信号 - Term 终止进程
    signal(SIGALRM, handler);
    // 设定一个闹钟
    alarm(1);
    
    while(true)
    {
        g_val++;
    }
    return 0;
}
*/



/*
int main()
{
    // 设定一个闹钟
    alarm(1);
    // 发送SIGALRM信号 - Term 终止进程
    int cnt = 0;
    while(true)
    {
        cout << "cnt: " << cnt++ << endl;
    }

}
*/



// mykill -9 pid
/*
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        cout << "Usage: " << argv[0] << " -signumber pid" << endl;
        return 1;
    }

    int signumber = stoi(argv[1] + 1); //拿到信号
    int pid = stoi(argv[2]); //拿到进程的pid

    int n = kill(pid, signumber);
    if(n < 0)
        cout << "kill error, " << strerror(errno) << endl;
    return 0;
}
*/